package com.github.wujichen158.andemusic.newcommands;

import com.github.wujichen158.andemusic.network.AndeMusicNetwork;
import com.github.wujichen158.andemusic.network.MusicMessage;
import com.github.wujichen158.andemusic.playernbt.MusicTypeProvider;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.text.TextFormatting;

import java.util.Optional;

public class SetAllMusicCommand extends CommandsRoot {
    @Override
    public String getName() {
        return "setallmusic";
    }

    @Override
    public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws WrongUsageException {
        if (args.length == 1) {
            changeMusic(args[0], sender, null, null, server);
        } else if (args.length == 3) {
            changeMusic(args[0], sender, args[1], args[2], server);
        } else {
            send(sender, TextFormatting.YELLOW, "commands.setall.usage");
        }
    }

    public void changeMusic(String musicType, ICommandSender sender, String minTime, String maxTime,
                            MinecraftServer server) throws WrongUsageException {
        try {
            int[] delayTimes = SetMusicCommand.tryGetDelayTimes(minTime, maxTime);
            int rMin = delayTimes[0];
            int rMax = delayTimes[1];

            for (String playerName : server.getOnlinePlayerNames()) {
                EntityPlayerMP player = getPlayer(server, sender, playerName);
                Optional.ofNullable(MusicTypeProvider.get(player)).ifPresent(nbt -> {
                    nbt.setMusicType(musicType);
                    nbt.setMinDelayTime(rMin);
                    nbt.setMaxDelayTime(rMax);

                    AndeMusicNetwork.INSTANCE.sendTo(new MusicMessage(musicType, rMin, rMax), player);
                });
            }

            send(sender, TextFormatting.GREEN, "commands.setall.success", musicType, rMin, rMax);
        } catch (Exception e) {
            throw new WrongUsageException("commands.setall.usage");
        }
    }
}